import React, { useState, useEffect } from 'react';
import type { ChangeEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import './LoginPage.css';
import { Input, Button, Checkbox, Modal, Spin, message } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import axios from 'axios';
import { QRCodeSVG } from 'qrcode.react';

const LoginPage: React.FC = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [use, setUse] = useState('');
    const [pwd, setPwd] = useState('');
    const [rememberMe, setRememberMe] = useState(false);
    const [captcha, setCaptcha] = useState('');
    const [userCaptcha, setUserCaptcha] = useState('');
    const [showQQLogin, setShowQQLogin] = useState(false);
    const [qqLoginType, setQqLoginType] = useState<'quick' | 'qr'>('quick');
    const [qrCodeUrl, setQrCodeUrl] = useState('');
    const [qrCodeStatus, setQrCodeStatus] = useState<'waiting' | 'scanning' | 'success' | 'expired'>('waiting');
    const [countdown, setCountdown] = useState(30);
    const navigate = useNavigate();

    // 生成随机验证码
    const generateCaptcha = () => {
        const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let result = '';
        for (let i = 4; i > 0; i--) {
            result += chars[Math.floor(Math.random() * chars.length)];
        }
        setCaptcha(result);
    };

    const login = async () => {
        let data = await axios.post(`http://localhost:3000/login`);
        if (data.data.code === 200) {
            setUse(data.data.data[0].username);
            setPwd(data.data.data[0].password);
            console.log(data.data.data[0].username);
        }
    };

    // 检查QQ是否已登录
    const checkQQLogin = () => {
        // 方法1: 检查localStorage中的测试状态
        const qqLoginStatus = localStorage.getItem('qq_login_status');
        if (qqLoginStatus === 'logged_in') {
            return true;
        }

        // 方法2: 尝试检测QQ客户端进程（仅限Windows）
        if (navigator.platform.indexOf('Win') !== -1) {
            // 在Windows上尝试检测QQ进程
            try {
                // 这里可以尝试检测QQ相关进程
                // 由于浏览器安全限制，我们使用其他方法
                const qqProcessCheck = localStorage.getItem('qq_process_detected');
                if (qqProcessCheck === 'true') {
                    return true;
                }
            } catch (error) {
                console.log('无法检测QQ进程');
            }
        }

        // 方法3: 检查QQ登录历史记录
        const qqLoginHistory = localStorage.getItem('qq_login_history');
        if (qqLoginHistory) {
            const lastLoginTime = parseInt(qqLoginHistory);
            const now = Date.now();
            // 如果24小时内登录过QQ，认为可能已登录
            if (now - lastLoginTime < 24 * 60 * 60 * 1000) {
                return true;
            }
        }

        // 方法4: 检查是否有QQ相关的cookie或存储
        const qqCookies = document.cookie.split(';').some(cookie =>
            cookie.trim().toLowerCase().includes('qq') ||
            cookie.trim().toLowerCase().includes('tencent')
        );
        if (qqCookies) {
            return true;
        }

        // 方法5: 尝试检测QQ浏览器扩展
        try {
            if ((window as any).qqExtension || (window as any).QQLogin) {
                return true;
            }
        } catch (error) {
            console.log('无法检测QQ扩展');
        }

        // 方法6: 检查是否有QQ相关的localStorage
        const qqRelatedKeys = Object.keys(localStorage).filter(key =>
            key.toLowerCase().includes('qq') ||
            key.toLowerCase().includes('tencent')
        );
        if (qqRelatedKeys.length > 0) {
            return true;
        }

        return false;
    };

    // 处理QQ登录
    const handleQQLogin = async () => {
        const isQQLoggedIn = checkQQLogin();
        console.log('QQ登录状态检测结果:', isQQLoggedIn);

        if (isQQLoggedIn) {
            // 如果QQ已登录，直接快捷登录
            setQqLoginType('quick');
            setShowQQLogin(true);
            try {
                // 模拟快捷登录过程
                await new Promise(resolve => setTimeout(resolve, 1500));
                // 保存登录状态
                localStorage.setItem('token', 'qq_auth_token');
                localStorage.setItem('login_type', 'qq');
                localStorage.setItem('qq_login_history', Date.now().toString());
                // 关闭弹窗并跳转
                setShowQQLogin(false);
                navigate('/about', { replace: true });
            } catch (error) {
                console.error('QQ快捷登录失败:', error);
                message.error('QQ快捷登录失败，请重试');
            }
        } else {
            // 如果QQ未登录，显示扫码登录
            setQqLoginType('qr');
            setShowQQLogin(true);
            generateQRCode();
        }
    };

    // 快捷登录

    // 生成二维码
    const generateQRCode = () => {
        const loginData = {
            type: 'qq_login',
            timestamp: Date.now(),
            sessionId: Math.random().toString(36).substring(2, 15),
            action: 'login'
        };

        const qrData = JSON.stringify(loginData);
        setQrCodeUrl(qrData);
        setQrCodeStatus('waiting');
        setCountdown(30);
        checkQRCodeStatus();
    };

    // 检查二维码扫描状态
    const checkQRCodeStatus = () => {
        let countdownTimer: ReturnType<typeof setInterval>;
        let checkStatusTimer: ReturnType<typeof setInterval>;

        // 倒计时
        countdownTimer = setInterval(() => {
            setCountdown(prev => {
                if (prev <= 1) {
                    clearInterval(countdownTimer);
                    setQrCodeStatus('expired');
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);

        // 模拟轮询检查二维码扫描状态
        checkStatusTimer = setInterval(async () => {
            try {
                // 这里应该调用后端API检查扫码状态
                // 目前用随机模拟扫描成功
                const isScanned = Math.random() > 0.95; // 5%概率模拟扫描成功
                if (isScanned) {
                    clearInterval(checkStatusTimer);
                    clearInterval(countdownTimer);
                    setQrCodeStatus('success');

                    // 保存登录状态
                    localStorage.setItem('token', 'qq_auth_token');
                    localStorage.setItem('login_type', 'qq');
                    localStorage.setItem('qq_login_history', Date.now().toString());

                    // 等待1.5秒展示成功状态，然后跳转
                    await new Promise(resolve => setTimeout(resolve, 1500));
                    setShowQQLogin(false);
                    navigate('/about', { replace: true });
                }
            } catch (error) {
                console.error('检查扫码状态失败:', error);
                message.error('检查扫码状态失败，请重试');
            }
        }, 1000); // 每秒检查一次

        // 30秒后停止检查，二维码过期
        const expireTimer = setTimeout(() => {
            clearInterval(checkStatusTimer);
            clearInterval(countdownTimer);
            setQrCodeStatus('expired');
        }, 30000);

        // 组件卸载时清理所有定时器
        return () => {
            clearInterval(checkStatusTimer);
            clearInterval(countdownTimer);
            clearTimeout(expireTimer);
        };
    };

    // 用户名校验
    const isValidUsername = (name: string) => /^[a-zA-Z0-9_]{4,16}$/.test(name);
    // 密码校验
    const isValidPassword = (pwd: string) => /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+]{8,20}$/.test(pwd);
    // 验证码校验
    const isValidCaptcha = (code: string) => /^[A-Z0-9]{4}$/.test(code);

    const MAX_ATTEMPTS = 5;
    const LOCK_TIME = 10 * 60 * 1000; // 10分钟

    const getLoginAttempts = () => {
        const data = localStorage.getItem('login_attempts');
        return data ? JSON.parse(data) : { count: 0, lastFail: 0 };
    };

    const setLoginAttempts = (count: number, lastFail: number) => {
        localStorage.setItem('login_attempts', JSON.stringify({ count, lastFail }));
    };

    // 检查是否已有token，如果有则直接跳转到主页
    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            navigate('/about', { replace: true });
            return;
        }

        const savedUsername = localStorage.getItem('username');
        const savedPassword = localStorage.getItem('password');
        if (savedUsername && savedPassword) {
            setUsername(savedUsername);
            setPassword(savedPassword);
            setRememberMe(true);
        }
        login();
        generateCaptcha();
    }, [navigate]);

    const handleLogin = async () => {
        const { count, lastFail } = getLoginAttempts();
        const now = Date.now();
        if (count >= MAX_ATTEMPTS && now - lastFail < LOCK_TIME) {
            alert('登录失败次数过多，请10分钟后再试');
            return;
        }
        if (!isValidUsername(username)) {
            alert('用户名格式不正确，需4-16位字母、数字或下划线');
            return;
        }
        if (!isValidPassword(password)) {
            alert('密码格式不正确，需8-20位且包含字母和数字');
            return;
        }
        if (!isValidCaptcha(userCaptcha)) {
            alert('验证码格式不正确');
            return;
        }
        if (!userCaptcha) {
            alert('请输入验证码');
            return;
        }
        if (userCaptcha.toUpperCase() !== captcha.toUpperCase()) {
            alert('验证码错误');
            generateCaptcha();
            return;
        }
        if (username !== use) {
            // 登录失败计数
            if (now - lastFail > LOCK_TIME) {
                setLoginAttempts(1, now);
            } else {
                setLoginAttempts(count + 1, now);
            }
            alert('用户名错误');
            return;
        }
        if (password !== pwd) {
            // 登录失败计数
            if (now - lastFail > LOCK_TIME) {
                setLoginAttempts(1, now);
            } else {
                setLoginAttempts(count + 1, now);
            }
            alert('密码错误');
            return;
        }
        // 登录成功，清除失败记录
        localStorage.removeItem('login_attempts');
        localStorage.setItem('token', 'your_auth_token_here'); // 替换为实际token
        if (rememberMe) {
            localStorage.setItem('username', username);
            localStorage.setItem('password', password);
        } else {
            localStorage.removeItem('username');
            localStorage.removeItem('password');
        }
        console.log('登录成功', { username, password });
        navigate('/about', { replace: true });
    };

    return (
        <div className="login-container">
            {/* 左侧背景图片区域 */}
            <div className="login-bg"></div>

            {/* 右侧登录表单区域 */}
            <div className="login-form-container">
                {/* 公司Logo */}
                <div className="company-logo">
                    <div className="logo-icon"></div>
                    <span className="logo-text">Arco Pro</span>
                </div>

                {/* 登录表单 */}
                <div className="login-form">
                    <div className="input-group">
                        <Input
                            placeholder="账号"
                            value={username}
                            onChange={(e: ChangeEvent<HTMLInputElement>) => setUsername(e.target.value)}
                            className="login-input"
                        />
                    </div>

                    <div className="input-group">
                        <Input.Password
                            placeholder="密码"
                            value={password}
                            onChange={(e: ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}
                            className="login-input"
                        />
                    </div>

                    {/* 添加验证码输入区域 */}
                    <div className="input-group captcha-group">
                        <Input
                            placeholder="验证码"
                            value={userCaptcha}
                            onChange={(e: ChangeEvent<HTMLInputElement>) => setUserCaptcha(e.target.value)}
                            className="login-input captcha-input"
                        />
                        <div className="captcha-display"
                            onClick={generateCaptcha}>
                            {captcha}
                        </div>
                    </div>

                    {/* 记住密码和忘记密码 */}
                    <div className="login-options">
                        <Checkbox
                            checked={rememberMe}
                            onChange={(e: CheckboxChangeEvent) => setRememberMe(e.target.checked)}
                            className="remember-checkbox"
                        >
                            记住密码
                        </Checkbox>
                        <button
                            className="forgot-password"
                            onClick={() => navigate('/register')} // 修改此处的跳转路径
                        >
                            注册账户
                        </button>
                    </div>

                    {/* 登录按钮 */}
                    <Button
                        type="primary"
                        onClick={handleLogin}
                        className="login-button"
                    >
                        立即登录
                    </Button>

                    {/* QQ登录按钮 */}
                    <div className="qq-login-section">
                        <div className="divider">
                            <span>或</span>
                        </div>
                        <Button
                            type="primary"
                            onClick={handleQQLogin}
                            className="qq-login-button"
                        >
                            <span className="qq-icon">🐧</span>
                            QQ登录
                        </Button>
                    </div>
                </div>

                {/* 底部警告信息 */}
                <div className="copyright-info">
                    警告：本软件受中国专利与国际公约保护，未经授权擅自复制全部或部分内容，将接受法律的严厉惩罚！V.20230129
                </div>
            </div>

            {/* QQ登录模态框 */}
            <Modal
                open={showQQLogin}
                onCancel={() => setShowQQLogin(false)}
                title={qqLoginType === 'quick' ? 'QQ快捷登录' : 'QQ扫码登录'}
                footer={null}
            >
                <div className="qq-login-modal">
                    {qqLoginType === 'quick' ? (
                        <div className="quick-login">
                            <Spin size="large" />
                            <p>正在使用QQ快捷登录...</p>
                        </div>
                    ) : (
                        <div className="qr-login">
                            <div className="qr-code-container">
                                {qrCodeStatus === 'success' ? (
                                    <div className="qr-success">
                                        <div className="success-icon">✓</div>
                                        <p>登录成功！</p>
                                    </div>
                                ) : (
                                    <div style={{
                                        width: 200,
                                        height: 200,
                                        display: 'flex',
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                        background: '#fff',
                                        margin: '0 auto'
                                    }}>
                                        {qrCodeStatus === 'waiting' && qrCodeUrl ? (
                                            <QRCodeSVG
                                                value={qrCodeUrl}
                                                size={200}
                                                level="H"
                                                includeMargin={true}
                                            />
                                        ) : qrCodeStatus === 'expired' ? (
                                            <div className="expired-qr">
                                                <p>二维码已过期</p>
                                            </div>
                                        ) : (
                                            <Spin size="large" />
                                        )}
                                    </div>
                                )}
                            </div>

                            {qrCodeStatus === 'waiting' && (
                                <div className="qr-status">
                                    <p>请使用QQ扫描二维码登录</p>
                                    <p className="countdown">二维码将在 {countdown} 秒后过期</p>
                                </div>
                            )}

                            {qrCodeStatus === 'expired' && (
                                <div className="qr-status">
                                    <p className="expired-text">二维码已过期</p>
                                    <p>请点击下方按钮刷新二维码</p>
                                </div>
                            )}

                            {qrCodeStatus === 'success' && (
                                <div className="qr-status">
                                    <p className="success-text">登录成功，正在跳转...</p>
                                </div>
                            )}

                            <Button
                                type="primary"
                                onClick={generateQRCode}
                                className="refresh-qr-button"
                                disabled={qrCodeStatus === 'success'}
                            >
                                {qrCodeStatus === 'expired' ? '刷新二维码' : '重新生成'}
                            </Button>
                        </div>
                    )}
                </div>
            </Modal>
        </div>
    );
};

export default LoginPage;
